package com.example.administrator.liveapp.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.example.administrator.liveapp.ApplicationUtils;
import com.example.administrator.liveapp.MainActivity;
import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.Xutils3.BitnapUtils;
import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.bean.JsonBean;
import com.example.administrator.liveapp.bean.MyFragmentBean;
import com.example.administrator.liveapp.utils.AlbumImagePath;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.utils.FileUtils;
import com.example.administrator.liveapp.utils.GetJsonDataUtil;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

import static android.R.attr.id;

/**
 * 修改上传头像activity
 */

public class ModifyPersonalInformationPage extends AppCompatActivity implements View.OnClickListener {

    private final int ADD_NAME = 1;
    private final int ADD_PROFESSIONAL = 2;
    private final int ADD_SIGNATURE = 3;
    private final int MSG_LOAD_DATA = 0x0001;
    private final int MSG_LOAD_SUCCESS = 0x0002;
    private final int MSG_LOAD_FAILED = 0x0003;
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private boolean isLoaded = false;
    private TextView textData;//显示省市区

    private final int PHOTO_CLIP = 113;//调用系统中自带的图片剪裁的请求code
    private final int FROM_CAMERA_CODE = 111;// 调用相机更改背景图片的请求code
    private final int FROM_ALBUM_CODE = 112;// 调用相册更改背景图片的请求code
    private PopupWindow mPopWindow;
    private TextView name, professional, signature;//姓名,职业,个性签名
    private RoundedImageView imageview;
    private String consumerId;//用户id
    private MyFragmentBean bean;


    //第二种拍照、选取图片
    private String[] permissions = new String[3];


    public ModifyPersonalInformationPage() {
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.modify_personal_information_page);
        ApplicationUtils applicationUtils = new ApplicationUtils();
        applicationUtils.addActivity(this);
        initView();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

//                        Toast.makeText(PersonalInformationPage.this,"开始解析数据",Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
//                    Toast.makeText(PersonalInformationPage.this,"解析数据成功",Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
//                    Toast.makeText(PersonalInformationPage.this,"解析数据失败",Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };

    private void initView() {
        Intent intent = getIntent();
        consumerId = intent.getStringExtra("consumerId");
        FileUtils.init();
        permissions[0] = Manifest.permission.READ_EXTERNAL_STORAGE;
        permissions[1] = Manifest.permission.WRITE_EXTERNAL_STORAGE;
        permissions[2] = Manifest.permission.CAMERA;
        mFilePath = FileUtils.getFileDir() + File.separator;
        textData = (TextView) findViewById(R.id.text_data);
        imageview = (RoundedImageView) findViewById(R.id.comments_head_portrait);
        name = (TextView) findViewById(R.id.name);
        professional = (TextView) findViewById(R.id.professional);
        signature = (TextView) findViewById(R.id.signature);
        findViewById(R.id.upload_picture).setOnClickListener(this);
        findViewById(R.id.btn_show).setOnClickListener(this);
        findViewById(R.id.save_title).setOnClickListener(this);
        findViewById(R.id.login_return).setOnClickListener(this);
        findViewById(R.id.rl_name).setOnClickListener(this);
        findViewById(R.id.rl_professional).setOnClickListener(this);
        findViewById(R.id.rl_signature).setOnClickListener(this);
        MyPageData();
    }

    private void MyPageData() {
        String url = AppUrl.URL + AppUrl.MyPageURL;
        Map<String, String> map = new HashMap<>();
        map.put("consumerId", consumerId);
        XUtils.Get(url, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String code = jsonObject.optString("code");
                if (code.equals("4800")) {
                    Gson gson = new Gson();
                    bean = gson.fromJson(result, MyFragmentBean.class);
                    if (bean.getConsumerphoto() != null && !bean.getConsumerphoto().equals("")) {
                        String str = bean.getConsumerphoto();
                        String photo = str.substring(0, 4);
                        if (photo.equals("http")) {
                            ImageLoader.getInstance().displayImage(bean.getConsumerphoto(), imageview);
                        } else {
                            ImageLoader.getInstance().displayImage(AppUrl.URL + bean.getConsumerphoto(), imageview);
                        }
                    }
                    name.setText(bean.getConsumername());
                    signature.setText(bean.getSign());
                    textData.setText(bean.getAddress());
                    professional.setText(bean.getConsumercareer());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Toast.makeText(ModifyPersonalInformationPage.this, "联网请求失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

//    private void showPopupWindow() {
//        //设置contentView
//        View contentView = LayoutInflater.from(ModifyPersonalInformationPage.this).inflate(R.layout.uploadpopupwindow, null);
//        mPopWindow = new PopupWindow(contentView,
//                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
//        mPopWindow.setContentView(contentView);
//        //设置各个控件的点击响应
//        TextView tv1 = (TextView) contentView.findViewById(R.id.pop_computer);
//        TextView tv2 = (TextView) contentView.findViewById(R.id.pop_financial);
//        TextView tv3 = (TextView) contentView.findViewById(R.id.pop_manage);
//        tv1.setOnClickListener(this);
//        tv2.setOnClickListener(this);
//        tv3.setOnClickListener(this);
//        //显示PopupWindow
//        View rootview = LayoutInflater.from(ModifyPersonalInformationPage.this).inflate(R.layout.modify_personal_information_page, null);
//        showPopmenu(rootview);
//    }

    /**
     * 图片上传的弹出popwindow
     *
     * @param rootview
     */
//    private void showPopmenu(View rootview) {
//        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                WindowManager.LayoutParams lp = getWindow().getAttributes();
//                lp.alpha = 1f;
//                getWindow().setAttributes(lp);
//            }
//        });
//        // 显示窗口位置
//        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//        // 设置layout在PopupWindow中显示的位置
//        WindowManager.LayoutParams lp = getWindow().getAttributes();
//        lp.alpha = 0.4f;
//        getWindow().setAttributes(lp);
//    }


    public String mPictureFile;
    public String filePath;
    private String mFilePath;
    private String mFileName;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.upload_picture:
//                showPopupWindow();//弹出拍照上传头像窗口
                if (!checkPermissions(permissions)) {
                    ActivityCompat.requestPermissions(ModifyPersonalInformationPage.this, permissions, 0);
                } else {
                    pickImage();
                }
                break;
            case R.id.btn_show:
                if (isLoaded) {
                    ShowPickerView();
                }
                break;
            case R.id.login_return:
                finish();
                break;
            case R.id.save_title:
                upLoadFile();
                break;
            case R.id.rl_name://添加姓名
                Intent intentName = new Intent(ModifyPersonalInformationPage.this, InputBoxPage.class);
                intentName.putExtra("title", "姓名");
                intentName.putExtra("result", ADD_NAME);
                intentName.putExtra("name", name.getText().toString());
                startActivityForResult(intentName, ADD_NAME);
                break;
            case R.id.rl_professional://添加职业
                Intent intentProfessional = new Intent(ModifyPersonalInformationPage.this, InputBoxPage.class);
                intentProfessional.putExtra("title", "职业");
                intentProfessional.putExtra("result", ADD_PROFESSIONAL);
                intentProfessional.putExtra("name", professional.getText().toString());
                startActivityForResult(intentProfessional, ADD_PROFESSIONAL);
                break;
            case R.id.rl_signature://添加个性签名
                Intent intentSignature = new Intent(ModifyPersonalInformationPage.this, InputBoxPage.class);
                intentSignature.putExtra("title", "个性签名");
                intentSignature.putExtra("result", ADD_SIGNATURE);
                intentSignature.putExtra("name", signature.getText().toString());
                startActivityForResult(intentSignature, ADD_SIGNATURE);
                break;
        }

        /**
         * 拍照,选择相册中的图片
         */
//        switch (v.getId()) {
//            //拍照
//            case R.id.pop_computer:
//                mPopWindow.dismiss();
////                // 调用系统相机
////                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
////                intent.addCategory(Intent.CATEGORY_DEFAULT);
////                // 取当前时间为照片名
////                mPictureFile = DateFormat.format("test",
////                        Calendar.getInstance(Locale.CHINA))
////                        + ".jpg";
////                Log.d("onactivity", "mPictureFile：" + mPictureFile);
////                filePath = getPhotoPath() + mPictureFile;
////                // 通过文件创建一个uri中
////                Uri imageUri = Uri.fromFile(new File(filePath));
////                // 保存uri对应的照片于指定路径
////                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//
////                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
////                intent.addCategory(Intent.CATEGORY_DEFAULT);
////                // 判断存储卡是否可以用，可用进行存储
////                if (hasSdcard()) {
////                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
////                            Environment.getExternalStorageDirectory(), "test.jpg")));
////                }
////                startActivityForResult(intent, FROM_CAMERA_CODE);
//                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//                    File path = new File(mFilePath);
//                    if (!path.exists()) {
//                        path.mkdirs();
//                    }
//                    mFileName = System.currentTimeMillis() + ".jpg";
//                    File file = new File(path, mFileName);
//                    if (file.exists()) {
//                        file.delete();
//                    }
//                    filePath = mFilePath+mFileName;
//                    FileUtils.startActionCapture(this, file, FROM_CAMERA_CODE);
//                } else {
//                    Log.e("main", "sdcard not exists");
//                }
//                break;
//            //从相册中获取
//            case R.id.pop_financial:
//                mPopWindow.dismiss();
//                Intent intent2 = new Intent(Intent.ACTION_PICK,
//                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                startActivityForResult(intent2, FROM_ALBUM_CODE);
//                break;
//
//            case R.id.pop_manage:
//                mPopWindow.dismiss();
//                break;
//        }
    }

    /**
     * 调起选择图片功能
     */
    private void pickImage() {
        Intent intent = new Intent(ModifyPersonalInformationPage.this, MultiImageSelectorActivity.class);
        // 是否显示调用相机拍照
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);

        // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);

        startActivityForResult(intent, FROM_CAMERA_CODE);
    }


    @Override   //只要开发者调用了requestPermissions方法,就算用户勾选了"不再提示"框，也会回调本方法
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (checkPermissions(permissions)) {
            pickImage();
        } else {
            showReasonAndRequestAgainIfCouldbe();
        }
    }

    /**
     * 检查所需权限是否都授予
     *
     * @param permissions 权限数组
     * @return 判断结果
     */
    private boolean checkPermissions(String[] permissions) {
        for (String perm : permissions) {
            if (ActivityCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 弹出对话框向用户解释为何需要该权限，并尝试再次请求权限
     * <p>
     * 注:shouldShowRequestPermissionRationale(Activity activity,String permission)方法
     * 如果用户已经授予该权限，此方法将返回false。
     * 如果应用之前请求过此权限但用户拒绝了请求，此方法将返回 true。
     * 如果用户在过去拒绝了权限请求，并在权限请求系统对话框中选择了 Don't ask again 选项，此方法将返回 false。
     */
    private void showReasonAndRequestAgainIfCouldbe() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            new AlertDialog.Builder(this)
                    .setTitle("需要权限")
                    .setMessage("该功能需要您授予拍照权限")
                    .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(ModifyPersonalInformationPage.this, new String[]{Manifest.permission.CAMERA}, 0);
                        }
                    })
                    .setNegativeButton("拒绝", null)
                    .create().show();
        } else if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) && ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {//用户拒绝并勾选了“不再提示”框，跳转应用设置界面
            new AlertDialog.Builder(this)
                    .setTitle("需要权限")
                    .setMessage("该功能需要您授予拍照权限,请手动开启权限")
                    .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Uri packageURI = Uri.parse("package:" + getPackageName());
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton("拒绝", null)
                    .create().show();
        } else if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            new AlertDialog.Builder(this)
                    .setTitle("需要权限")
                    .setMessage("该功能需要读取您的内存卡上的图片")
                    .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(ModifyPersonalInformationPage.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
                        }
                    })
                    .setNegativeButton("拒绝", null)
                    .create().show();
        } else if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE) && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {//用户拒绝并勾选了“不再提示”框，跳转应用设置界面
            new AlertDialog.Builder(this)
                    .setTitle("需要权限")
                    .setMessage("该功能需要读取您的内存卡上的图片,请手动开启权限")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Uri packageURI = Uri.parse("package:" + getPackageName());
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                            startActivity(intent);
                        }
                    })
                    .create().show();
        }
    }

//    //将图片转换成字符串
//    private void saveBitmap(Bitmap bitmap) {
//        //第一步:将Bitmap压缩至字节数组输出流ByteArrayOutputStream
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//        bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
//        //第二步:利用Base64将字节数组输出流中的数据转换成字符串String
//        byte[] byteArray = byteArrayOutputStream.toByteArray();
//        result = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
//    }

    private File file;

    /**
     * 上传用户信息到服务器
     */
    private void upLoadFile() {
//        Toast.makeText(ModifyPersonalInformationPage.this,"Base64:"+result,Toast.LENGTH_SHORT).show();
        String urls = AppUrl.URL + AppUrl.personalInformation;
        Map<String, Object> map = new HashMap();
        map.put("consumerId", consumerId);
        map.put("consumerName", name.getText().toString());
        map.put("consumerCareer", professional.getText().toString());
        map.put("sign", signature.getText().toString());
        map.put("address", textData.getText().toString());
        map.put("file", file);
        XUtils.UpLoadFile(urls, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String code = jsonObject.optString("code");
                    String message = jsonObject.optString("message");
                    if (code.equals("60000")) {
                        Toast.makeText(ModifyPersonalInformationPage.this,"修改成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent();
                        intent.setClass(ModifyPersonalInformationPage.this, MainActivity.class);
                        startActivity(intent);
                    } else {
                        Toast.makeText(ModifyPersonalInformationPage.this,message+"修改失败" + consumerId, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(ModifyPersonalInformationPage.this, e.getMessage() + "异常", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Toast.makeText(ModifyPersonalInformationPage.this, ex.getMessage() + "修改错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

//    @Override
//    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
//        outState.putString("filePath", filePath);
//        Log.d("TAG", "onSaveInstanceState");
//    }
//
//    @Override
//    protected void onRestoreInstanceState(Bundle savedInstanceState) {
//        super.onRestoreInstanceState(savedInstanceState);
//        if (TextUtils.isEmpty(filePath)) {
//            filePath = savedInstanceState.getString("filePath");
//        }
//        Log.d("TAG", "onRestoreInstanceState");
//    }

    /**
     * 获得照片路径
     *
     * @return
     */
//    private String getPhotoPath() {
//        return Environment.getExternalStorageDirectory() + "/DCIM/";
//    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case FROM_CAMERA_CODE:
                if (resultCode == RESULT_OK) {
                    if (null != data) {
                        final List<String> list = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
//                        String compressImage = CompressImageUtils.compressImage(list.get(0), list.get(0), 40);
//                File f=new File("file://"+list.get(0));
                        Glide.with(ModifyPersonalInformationPage.this).load(Uri.fromFile(new File(list.get(0)))).into(imageview);
                        file = new File(BitnapUtils.compressImage(list.get(0), list.get(0), 30));
                    }
                }
//                Toast.makeText(this, file+"", Toast.LENGTH_SHORT).show();
//                Glide.with(ModifyPersonalInformationPage.this).load(Uri.fromFile(new File(list.get(0)))).asBitmap().into(new SimpleTarget<Bitmap>() {
//                    @Override
//                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
//                        Log.e("1111111"," "+list.get(0));
//                        saveBitmap(resource);
//                        imageview.setImageBitmap(resource);
//                    }
//                });
                break;
//            //相册
//            case FROM_ALBUM_CODE:
//                if (null != data) {
//                    // 得到图片的全路径
//                    Uri uri = data.getData();
//                    String imagePath = AlbumImagePath.getPath(this, uri);
//                    photoClip(data.getData());
//                }
//                break;
//            //拍照
//            case FROM_CAMERA_CODE:
//                if(resultCode == RESULT_OK){
//                    File path = new File(mFilePath);
//                    if (!path.exists()) {
//                        path.mkdirs();
//                    }
//                    File file = new File(path, mFileName);
//                    if (file.exists()) {
//                        photoClip(FileUtils.getUriForFile(this,file));
//                    }else{
//                        Toast.makeText(this, "没有", Toast.LENGTH_SHORT).show();
//                    }
//                }
//                break;
//            case PHOTO_CLIP:
//                if (data != null) {
//                    Bundle extras = data.getExtras();
//                    if (extras != null) {
//                        Bitmap photo = extras.getParcelable("data");
//                        imageview.setImageBitmap(photo);
//                        saveBitmap(photo);
//                    }
//                }
//                break;
//            default:
//                break;
        }
        switch (resultCode) {
            case ADD_NAME://添加姓名返回的code
                name.setText(data.getStringExtra("add"));
                break;

            case ADD_PROFESSIONAL://添加职位返回的code
                professional.setText(data.getStringExtra("add"));
                break;

            case ADD_SIGNATURE://添加个性签名返回的code
                signature.setText(data.getStringExtra("add"));
                break;
            default:
                break;
        }

    }

    /**
     * 调用系统中自带的图片剪裁
     *
     * @param uri
     */
//    private void photoClip(Uri uri) {
//        // 调用系统中自带的图片剪裁
//        Intent intent = new Intent("com.android.camera.action.CROP");
//        intent.setDataAndType(uri, "image/*");
//        // 设置在开启的Intent中设置显示的VIEW可裁剪
//        intent.putExtra("crop", "true");
//        // aspectX aspectY 是宽高的比例
//        intent.putExtra("aspectX", 1);
//        intent.putExtra("aspectY", 1);
//        // outputX outputY 是裁剪图片宽高
//        intent.putExtra("outputX", 150);
//        intent.putExtra("outputY", 150);
//        intent.putExtra("return-data", true);
//        startActivityForResult(intent, PHOTO_CLIP);
//    }

    /**
     * 判断sd卡是否存在
     *
     * @return
     */
//    public boolean hasSdcard() {
//        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            return true;
//        } else {
//            return false;
//        }
//    }


    /**
     * 省市区3级选择器
     */
    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);

                textData.setText(tx);
//                Toast.makeText(PersonalInformationPage.this,tx,Toast.LENGTH_SHORT).show();
            }
        })
                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setTitleColor(getResources().getColor(R.color.black))//标题文字颜色)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.main))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.main))//取消按钮文字颜色.build();
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

}
